//axiosInstance.js
//导入axios
import axios from "axios";
import { ElNotification } from "element-plus";
import { useUserStore } from "../store/userStore";

//使用axios下面的create([config])方法创建axios实例，其中config参数为axios最基本的配置信息。
// const serverURL = "http://localhost:8000"
const serverURL = import.meta.env.VITE_API_BASE_URL
console.log("API BASE URL::>",import.meta.env.VITE_API_BASE_URL)
// const serverURL = "http://localhost:5000/psy/api"
const API = axios.create({
  baseURL: serverURL, //请求后端数据的基本地址，自定义
  timeout: 20000000, //请求超时设置，单位ms
});
const baseURL = serverURL;
// const self = this
const controller = new AbortController();
export async function POST(url, method, data, notification, self = null, needLogin = false) {
  // // console.log(data);
  if (needLogin == true) {
    if (!useUserStore().userInfo) {

      ElNotification({
        title: "提示",
        type: "success",
        dangerouslyUseHTMLString: true,
        message: '请先登陆',
      });
      // return {code:-1,msg:'请先登录',data:{}}
      self.$router.push('/login')
    } else {
      data = { data: data, user: useUserStore().userInfo }
    }
  }
  console.log('上传的参数：：', data)
  let rs = {};
  rs = await API({
    url: baseURL + url,
    method: method,
    data: data,
  }).then((res) => {
    console.log("POST成功!", res);
    if (res.data.code == 200 && notification) {
      console.log("成功弹提示");
      ElNotification({
        title: "提示",
        type: "success",
        dangerouslyUseHTMLString: true,
        message: res.data.msg,
      });
    }
    console.log('RES:::', res)
    if (res.data.code != 200 && notification) {
      ElNotification({
        title: "提示",
        type: "warning",
        dangerouslyUseHTMLString: true,
        message: res.data.msg,
      });
    }
    return res.data;
  });
  return rs;
}

export async function streamPOST(url, data) {

  let req = await fetch(baseURL + url, {
    method: "POST",
    headers: {
      // "Accept-Encoding": "identity",
      "Content-Type": "application/json",
    },
    signal: controller.signal,
    body: JSON.stringify(data)
  });
  return req
}
export default API;
